from flask import Blueprint, request, jsonify
from App.models import models, Author, Book

view = Blueprint('blue', __name__)
json = {}

@view.route('/')
def index():
    return "Hello"


@view.route('/api/createdb')
def createDB():
    try:
        # 创建数据库
        models.drop_all()
        models.create_all()
        # 声明数据
        au1 = Author(name='老王')
        au2 = Author(name='老尹')
        au3 = Author(name='老刘')
        # 增加数据
        models.session.add_all([au1, au2, au3])
        # 提交数据
        models.session.commit()
        bk1 = Book(name='老王回忆录', author_id=au1.id)
        bk2 = Book(name='我读书少，你别骗我', author_id=au1.id)
        bk3 = Book(name='如何才能让自己更骚', author_id=au2.id)
        bk4 = Book(name='怎样征服美丽少女', author_id=au3.id)
        bk5 = Book(name='如何征服英俊少男', author_id=au3.id)
        models.session.add_all([bk1, bk2, bk3, bk4, bk5])
        models.session.commit()
        json["message"] = "0"
        return jsonify(json)
    except Exception as e:
        json["message"] = "数据库创建失败\n错误信息：" + str(e)
        return jsonify(json)


@view.route('/api/getdata')
def getdata():
    try:
        listData = []
        # 遍历书籍作者
        for item in Author.query.all():
            # 遍历书籍作者的书籍
            bookslist = []
            for book in Book.query.filter(Book.author_id == item.id).all():
                bookslist.append(book.name)
            listData.append({'id': item.id, 'name': item.name, 'books': bookslist})
        json["message"] = "0"
        json["data"] = listData
        return jsonify(json)
    except Exception as e:
        json["message"] = "数据获取失败\n错误信息：" + str(e)
        return jsonify(json)

@view.route('/api/addbook', methods=['POST', 'GET'])
def addbook():
    try:
        author = request.args['author']
        book = request.args['book']
        # 先查询作者是否存在
        if Author.query.filter(Author.name == author).first():
            # 判断书籍是否存在
            if Book.query.filter(Book.name == book):
                return "已存在同名书籍"
            else:
                bk = Book(author_id=Author.query.filter(Author.name == author).first().id, name=book)
                models.session.add(bk)
                models.session.commit()
        else:
            # 创建作者
            au = Author(name=author)
            models.session.add(au)
            models.session.commit()
            bk = Book(author_id=Author.query.filter(Author.name == author).first().id, name=book)
            models.session.add(bk)
            models.session.commit()
        json["message"] = "0"
        return jsonify(json)
    except Exception as e:
        json["message"] = "增加失败\n错误信息：" + str(e)
        return jsonify(json)

@view.route('/api/delbook', methods=['POST', 'GET'])
def delbook():
    author = request.args['author']
    book = request.args['book']
    try:
        authorID = Author.query.filter(Author.name == author).first().id
        bookID = Book.query.filter(Book.author_id == authorID and Book.name == book).first().id
        bk = Book.query.filter((Book.id==bookID)).first()
        models.session.delete(bk)
        models.session.commit()
        json["message"] = "0"
        return jsonify(json)
    except Exception as e:
        json["message"] = "删除失败\n错误信息：" + str(e)
        return jsonify(json)


@view.route('/api/delauthor', methods=['POST', 'GET'])
def delauthor():
    try:
        author = request.args['author']
        authorID = Author.query.filter(Author.name == author).first().id
        books = Book.query.filter(Book.author_id == authorID).all()
        for book in books:
            models.session.delete(book)
            models.session.commit()
        models.session.delete(Author.query.filter(Author.id == authorID).first())
        models.session.commit()
        json["message"] = "0"
        return jsonify(json)
    except Exception as e:
        json["message"] = "删除失败\n错误信息：" + str(e)
        return jsonify(json)

@view.route('/api/abc', methods=['POST', 'GET'])
def abc():
    json = {}
    # json["code"] = 
    json["message"] = "0"
    json["data"] = [{"a":"1", "b":"2"}]
    return jsonify(json)
